package com.feige.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.feige.pojo.User;
import com.feige.service.UserService;
import com.feige.utils.common.MD5;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 把xls，xlsx中的数据导入到数据库中
 * @author feige
 */
@Slf4j
public class UserDataListener extends AnalysisEventListener<User> {

    private static final int BATCH_COUNT = 10;
    List<User> userList = new ArrayList<>();

    private UserService userService;

    private Boolean updateSupport;


    public UserDataListener(UserService userService, Boolean updateSupport) {
        this.userService = userService;
        this.updateSupport = updateSupport;
    }

    @Override
    public void invoke(User data, AnalysisContext context) {
        //log.info("解析到一条数据:{}", JSON.toJSONString(data));
        String num = data.getNum();
        data.setPassword(MD5.encrypt(num));
        userList.add(data);
        if(userList.size() >= BATCH_COUNT){
            if (this.updateSupport){
                saveOrUpdateUser();
            }else {
                saveUser();
            }
            userList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (this.updateSupport){
            saveOrUpdateUser();
        }else {
            saveUser();
        }
        log.info("所有数据解析完成！");
    }

    private void saveOrUpdateUser(){
        log.info("{}条数据开始存入数据库", userList.size());
        userService.saveOrUpdateBatch(userList);
        log.info("存入完成");
    }

    private void saveUser(){
        log.info("{}条数据开始存入数据库", userList.size());
        userService.saveBatch(userList);
        log.info("存入完成");
    }
}
